package com.tudulist.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;

import com.tudulist.security.UserAuthenticatedWebSession;
import com.tudulist.web.utils.TudulistUtil;

@SuppressWarnings("serial")
public class LoginPage extends WebPage {

	private static Logger logger = Logger.getLogger(LoginPage.class);

	public LoginPage(PageParameters parameters) {
		add(new LoginForm("loginForm"));
	}

	private class LoginForm extends Form<Void> {

		private String username;

		private String password;

		private Boolean rememberMe;

		private FeedbackPanel feedBack;

		@SuppressWarnings({ "unchecked", "rawtypes" })
		public LoginForm(String id) {
			super(id);
			setModel(new CompoundPropertyModel(this));
			feedBack = new FeedbackPanel("feedback");
			feedBack.setOutputMarkupId(true);
			add(new RequiredTextField<String>("username"));
			add(new PasswordTextField("password"));
			add(new CheckBox("rememberMe", new PropertyModel<Boolean>(this, "rememberMe")));
			add(feedBack);
			add(new AjaxSubmitLink("submit") {
				@Override
				protected void onSubmit(AjaxRequestTarget target, Form form) {
					HttpServletRequest servletRequest = (HttpServletRequest) RequestCycle.get().getRequest().getContainerRequest();
					String originalUrl = TudulistUtil.getOriginalUrl(servletRequest.getSession());
					UserAuthenticatedWebSession session = (UserAuthenticatedWebSession) AuthenticatedWebSession.get();
					if (session.signIn(username, password, rememberMe)) {
						if (originalUrl != null) {
							logger.info(String.format("redirecting to %s", originalUrl));
							TudulistUtil.redirectToUrl(originalUrl);
						} else {
							logger.info("redirecting to home page");
							setResponsePage(getApplication().getHomePage());
						}
					} else {
						error("Login failed due to invalid credentials or role");
						setResponsePage(this.getPage());
					}
				}
			});
		}

	}
}
